package cn.chenfeifx.example.ui;

import cn.chenfeifx.core.common.FxUtil;
import cn.chenfeifx.core.common.ResourcesLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;

import java.util.Optional;

public class Reward extends StackPane {

    private static final String STYLE_SHEET = ResourcesLoader.load("/css/reward.css");

    private final ImageView imageView = new ImageView();

    private final ToggleGroup toggleGroup = new ToggleGroup();
    private final ToggleButton wx_but = new ToggleButton("微信");
    private final ToggleButton zfb_but = new ToggleButton("支付宝");
    private final HBox toggleButtonBox = new HBox(wx_but, zfb_but);

    public Reward() {
        setPadding(new Insets(20));
        setPrefSize(400, 400);
        getChildren().addAll(toggleButtonBox, imageView);
        StackPane.setAlignment(toggleButtonBox, Pos.TOP_CENTER);
        getStylesheets().add(STYLE_SHEET);
        toggleButtonBox.setMaxSize(USE_PREF_SIZE, USE_PREF_SIZE);
        //
        wx_but.getProperties().put("img", "/img/pay-wx.jpg");
        zfb_but.getProperties().put("img", "/img/pay-zfb.jpg");
        wx_but.setToggleGroup(toggleGroup);
        zfb_but.setToggleGroup(toggleGroup);
        wx_but.getStyleClass().add("wx-but");
        zfb_but.getStyleClass().add("zfb-but");
        toggleButtonBox.getStyleClass().add("toggle-button-box");
        //监听selected
        toggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == null) {
                toggleGroup.selectToggle(oldValue);
            }
            Optional.ofNullable(newValue)
                    .map(Toggle::getProperties)
                    .map(v -> v.get("img"))
                    .ifPresent(v -> imageView.setImage(FxUtil.getImage(v.toString())));
        });
        imageView.setFitHeight(260);
        imageView.setFitWidth(260);
        //
        wx_but.setSelected(true);
    }
}